<?php

class DatabaseFactory {

	var $oDatasource;
	
	function DatabaseFactory( &$oDatasource ) {
		$this->oDatasource = $oDatasource;
	}
	
	function ConstructDatabase() {
		
		$oDatabase = new Database();
		
		$this->ConstructTables( $oDatabase );
		$this->ConstructForeignKeys( $oDatabase );
		
		return $oDatabase;
	}
	
	function ConstructTables( &$oDatabase ) {
		foreach( $this->oDatasource->GetTableList() as $sThisTableName ) {
			$this->ConstructTable( $oDatabase, $sThisTableName );
		}
	}

	function ConstructForeignKeys( &$oDatabase ) {
		foreach( $oDatabase->GetTableNames() as $sThisTable ) {
			foreach( $this->oDatasource->GetForeignKeys( $sThisTable ) as $aThisKey ) {
				$this->ConstructForeignKey( $oDatabase, $aThisKey );
			}
		}
	}

	function ConstructForeignKey( &$oDatabase, $aKey ) {
		if ( isset( $aKey['NAME'] ) && isset( $aKey['FROM_TABLE'] ) && isset( $aKey['FROM_COLUMNS'] )
			&& isset( $aKey['TO_TABLE'] ) && isset( $aKey['MANDATORY'] ) ) {
			$oDatabase->AddForeignKey( $aKey['NAME'], $aKey['FROM_TABLE'], $aKey['FROM_COLUMNS'], $aKey['TO_TABLE'], $aKey['MANDATORY']=='1' );
		}
	}
	
	function ConstructTable( &$oDatabase, $sTableName ) {
	
		$oTable = new Table( $sTableName );
		$oDatabase->AddTable( $oTable );	
		
		foreach( $this->oDatasource->GetColumnList( $sTableName ) as $aThisColumn ) {
			if ( isset( $aThisColumn['NAME'] ) && isset( $aThisColumn['DATATYPE'] ) ) {
				$oTable->AddColumn( $aThisColumn['NAME'], $aThisColumn['DATATYPE'] );
			}
		}
		
		$aPrimaryKey = $this->oDatasource->GetPrimaryKey( $sTableName );
		if ( isset( $aPrimaryKey['NAME'] ) && isset( $aPrimaryKey['COLUMNS'] ) && is_array( $aPrimaryKey['COLUMNS'] ) && count( $aPrimaryKey['COLUMNS'] > 0 )) {
			$oTable->AddPrimaryKey( $aPrimaryKey['NAME'], $aPrimaryKey['COLUMNS'] );
		}
	}
}

require_once( 'Table.php' );
require_once( 'Database.php' );


?>
